package com.sss.demo.servlet;

import com.sss.demo.entity.Goods;
import com.sss.demo.service.GoodsService;
import com.sss.demo.service.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/*
*       *.goods 代表的是
*       /list.goods
*       /jsp/list.goods
*       /update.goods
*       也就是所有的后缀为goods的请求，都找此Servlet
* */
@WebServlet("*.goods")
public class GoodsServlet extends HttpServlet {
        GoodsService service;
        String uri;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        uri=getUri(req);
        switch (uri){
            case "list":
                String pageStr=req.getParameter("page");
                String countStr=req.getParameter("count");
                int page=0;
                int count=0;
                if(pageStr==null){
                    page=1;
                }else{
                    page=Integer.valueOf(pageStr);
                }
                if (countStr==null){
                    count=5;
                }else{
                    count=Integer.valueOf(countStr);
                }
                service=new GoodsServiceImpl();
                List<Goods> list =service.getGoodsList(page,count);
                //  总页数=获取商品的总数量/每页显示的数量
                int goodsCount=getList().size();
                int pageCount=goodsCount%count==0?goodsCount/count:goodsCount/count+1;
                req.getSession().setAttribute("pageCount",pageCount);
                req.getSession().setAttribute("list",list);
                String path=req.getContextPath();
                resp.sendRedirect(path+"/jsp/goods.jsp");
                break;
            default:break;
        }
    }

    private List<Goods> getList() {
        service=new GoodsServiceImpl();
        return service.getAllGoods();
    }

    private String getUri(HttpServletRequest req) {
        /*System.out.println("所有的后缀为goods的请求，都找GoodsServlet");*/
        //  /demo_war_exploded/jsp/list.goods
        //System.out.println(req.getRequestURI());
        String path=req.getRequestURI();
        int start=path.lastIndexOf("/")+1;
        int end=path.indexOf(".");
        return path.substring(start,end);
    }
}
